package org.extframework.ld.service.pojo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.extframework.ld.content.XmlContent;
import org.extframework.ld.content.model.XmlMenuNode;
import org.extframework.ld.exception.SysException;
import org.extframework.ld.service.SysManager;
import org.hibernate.Query;
import org.hibernate.Session;

/**
 * @author : Dong.Li
 * @created : 2013-1-17
 * @version : 1.0
 * @description :
 */
public class DefaultSysManager extends DefaultBaseManager implements SysManager {

	public Map<String, List<Object[]>> getObjects(String hql, int start,
			int size, Object... objs) {

		Map<String, List<Object[]>> reslutMap = new HashMap<String, List<Object[]>>();
		Session session = this.commDao.getHibernateTemplate()
				.getSessionFactory().openSession();

		for (Object obj : objs) {
			hql = hql.replaceFirst("\\?", "'" + obj + "'");
		}

		String regHql = hql.toUpperCase();
		int startIndex = regHql.indexOf("SELECT");
		int endIndex = regHql.indexOf("FROM");

		if ((startIndex <= -1) || (endIndex <= -1)) {
			throw new SysException("[" + hql + "] 解析语法错误 !");
		}

		String countHql = hql.toString();

		int orderIndex = regHql.indexOf("ORDER BY");
		if (orderIndex > -1) {
			countHql = hql
					.replace(hql.substring(orderIndex, hql.length()), " ");
		}
		int groupIndex = regHql.indexOf("GROUP");
		if (groupIndex > -1) {
			countHql = hql
					.replace(hql.substring(groupIndex, hql.length()), " ");
		}

		countHql = countHql.replace(hql.substring(startIndex, endIndex),
				"SELECT COUNT(*) ");
		
		Object objCount = session.createQuery(countHql).list().get(0);

		Query query = session.createQuery(hql);
		query.setFirstResult(start);
		query.setMaxResults(size);
		List os = query.list();
		if (session != null) {
			session.flush();
			session.clear();
			session.close();
		}
		reslutMap.put(objCount.toString(), os);
		return reslutMap;
	}


}
